<template>
  <div class="sso-login" v-loading.fullscreen.lock="true" element-loading-text="登录中..."></div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import authMgr from '../utils/auth'
import router from '@/router/index'

import { useInstance } from '@runwork/runwork-help'
const runwork = useInstance()

let tryCounter = 0

onMounted(() => {
  console.log('SSOLoginView onMounted')
  tryCounter = 0
  console.log('sso-rwork start initReady')
  runwork
    .initReady()
    .then(() => {
      //调用示例
      console.log('sso-rwork initReady complete[user]:', runwork.user)
      // console.log('sso-rwork user:', runwork.user)
      // console.log('sso-rwork ladp:', runwork.ladp)
      // console.log('sso-rwork token:', runwork.runWorkToken)
      tryLogin()
    })
    .catch((error: any) => {
      console.error('runwork initReady error:', error)
      let errMessage = error.errMsg
      if (error.errCode === 10228) {
        errMessage = '没有访问此应用的权限'
      }
      ElMessageBox.alert(`${errMessage}，SDK初始化失败，请联系管理员`, '温馨提示', {
        confirmButtonText: '确定'
      })
    })
})

function tryLogin() {
  tryCounter++

  if (tryCounter > 20) {
    ElMessageBox.alert('SDK初始化失败，请关闭应用后重新打开应用', '温馨提示', {
      confirmButtonText: '确定'
    })
    return
  }

  let rworkToken = runwork.runWorkToken as string
  let user = runwork.user as {}
  if (rworkToken) {
    console.log('tryLogin:', rworkToken)
    try {
      authMgr.ssoLogin(rworkToken, user).then((result) => {
        console.log(result)
        router.push('/')
      })
    } catch (e) {
      console.log('tryLogin error:', e)
    }
    return
  }

  setTimeout(() => {
    tryLogin()
  }, 200)
}
</script>

<style lang="scss" scoped>
.sso-login {
  height: 100%;
  width: 100%;
}
</style>
